package com.hl.toolkit.server.bdpay;


import com.alibaba.fastjson.JSONObject;
import com.util.LoadProperties;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;

public class O2o_CodeCreateServlet  { 
 
	
	private ServletConfig scon = null;
	
	public O2o_CodeCreateServlet() {
		super();
	}
	
 

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	/**
	 *接收o2o_codecreate.html页面的post请求
	 * 
	 */
	public String doPost(HttpServletRequest request, HttpServletResponse response,String order_no,String order_create_time)
			throws ServletException, IOException {
		 /**
         * 1、设置编码
         */
		
		String resultStr="";
		request.setCharacterEncoding("gbk");
		response.setCharacterEncoding("gbk");
		response.setContentType("text/html;charset=gbk");  
		response.setHeader("content-type","text/html;charset=gbk");
	 //PrintWriter out = response.getWriter();
		//打印日志
	//	Logger logger =new  BfbSdkComm().printLog("O2o_CodeCreateServlet");

		/**
		 * 2、获取 web.xml内的常量值
	     */
		
	    
	    //商户号
	    String sp_no="sp_no="+BaiduConfig.spNo;
	    //交易的超时时间,当前时间加2天
	    Calendar   c   =   Calendar.getInstance(); 
	    c.add(Calendar.DAY_OF_MONTH, 2);  
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");  
        String mDateTime=formatter.format(c.getTime());  
	    String strExpire=mDateTime.substring(0, 14);//
	    String expire_time=
	    		"expire_time=" +strExpire;
	    //订单创建时间
	    //String order_create_time1=formatter.format(System.currentTimeMillis()); 
	    //订单号
	      order_create_time="order_create_time=" +order_create_time;
	      order_no="order_no="+order_no;
	    
	    
	    
	  //商品分类号
		    String  service_code= "service_code=1";
 	  
		//实体商户门店名称
	   // String mname="mname="+ request.getParameter("mname");	
	 //   String mname1="mname="+ URLEncoder.encode(request.getParameter("mname"),"gbk");
		//实体终端名称
		//String tno="tno="+request.getParameter("tno");
	//	String mno="mno="+request.getParameter("mno");
		    String currency="currency=1";
		    //编码
		    String input_charset="input_charset=1";
		    //版本
		    String version="version=2";
	    //加密方式md5或者hash
	    String sign_method="sign_method=1";
	    //提交地址
	    String BFB_PAY_DIRECT_O2O_CREATE_URL=BaiduConfig.BaiduAddressCreateCode;
	    //商品名称
	    String tempgoods_name=request.getParameter("goods_name");
	    String goods_name ="goods_name="+tempgoods_name;
	    String goods_name1="goods_name="+ URLEncoder.encode(request.getParameter("goods_name"),"gbk");
	    //商品描述
 	    String goods_desc ="goods_desc=万众汇聚";
	   String goods_desc1= "goods_desc="+URLEncoder.encode("万众汇聚","gbk");
	    //商品在商户网站上的URL
	   
	    String goods_url ="page_url="+LoadProperties.loadPropertiesValue("applicationURL")+"/tycoinPayApp/app_systemSuccess";
 	    String goods_url1="page_url="+URLEncoder.encode(LoadProperties.loadPropertiesValue("applicationURL")+"/tycoinPayApp/app_systemSuccess","gbk");
 
	    //支付方式
	    String pay_type = "pay_type=2";
	    //单价
	 //   String unit_amount ="unit_amount="+request.getParameter("unit_amount");
	    //数量
	 //   String unit_count ="unit_count="+request.getParameter("unit_count");
	    //运费
	 //   String transport_amount ="transport_amount="+request.getParameter("transport_amount");
	    //总金额
	    String total_amount ="total_amount="+request.getParameter("total_amount");
	   //后台通知地址
	      String return_url ="return_url="+BaiduConfig.SSLapplicationNotiyReturnUrl;
	 	    String return_url1="return_url="+URLEncoder.encode(BaiduConfig.SSLapplicationNotiyReturnUrl,"gbk");
     
	    //商户自定义数据
	   // String tempextra=request.getParameter("extra");
	  //  String extra ="extra="+tempextra;
	 //   String extra1="extra="+URLEncoder.encode(tempextra,"gbk");
	
	    
	    //签名串拼接数组
		String[]array={
			    service_code,
				sp_no,
				order_create_time,
				order_no,
				goods_name,
			 goods_desc,
				goods_url,
			//	unit_amount,
			//	unit_count,
			//	transport_amount,
				total_amount,
				pay_type,
			//	mno,
			//	tno,
				//mname,
				currency,
				return_url,
				expire_time,
				input_charset,
				version,
				sign_method
			//	,extra
				};
		//浏览器参数拼接数组
		String[]array1={
			//	mname1,
				//tno,
			//	mno,
			    service_code,
				sp_no,
				order_create_time,
				order_no,
				pay_type,
				goods_name1,
				goods_desc1,
				goods_url1,
			//	unit_amount,
				//unit_count,
			//	transport_amount,
				total_amount,
				currency,
				return_url1,
				expire_time,
				input_charset,
				version,
				sign_method
			//	extra1
				};
		/**
		 * 4、调用bfb_sdk_comm里create_bdpay_pay_order_url方法生成百度钱包扫码支付接口URL
		 *   array是待签名串
		 *   array1地址栏拼接串
		 *   
		 */
		String getURL=new BfbSdkComm().create_bdpay_pay_order_url(array,array1,BFB_PAY_DIRECT_O2O_CREATE_URL);
		 /**
         * 5、向百付宝发起订单支付请求
         */
	    HttpClient httpClient =  new  HttpClient();    
	    httpClient.getParams().setParameter(
	    	      HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
	    // 设置 Http 连接超时为5秒    
	    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 5000 );   
	     /* 生成 GetMethod 对象并设置参数 */    
	    GetMethod getMethod =  new  GetMethod(getURL);    
	     // 设置 get 请求超时为 5 秒    
	    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,  5000 );   
	      // 设置请求重试处理，用的是默认的重试处理：请求三次    
	    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new  DefaultHttpMethodRetryHandler());         
	    String responseStr = "" ;    
	     /**
	      * 6、 执行 HTTP GET 请求
	      */ 
	     try  
	     {    
	         int  statusCode = httpClient.executeMethod(getMethod); 
	         /*  判断访问的状态码 */    
	         if  (statusCode != HttpStatus.SC_OK) 
	         {    
	           System.out.println( "HttpStatus.SC_OK :" + getMethod.getStatusLine());   
	          }    
	     
	        // HTTP响应头部信息，这里简单打印                 	         
	        // 读取 HTTP 响应内容，这里简单打印网页内容    
           
            InputStream ins = getMethod.getResponseBodyAsStream();
            

          BufferedReader br = new BufferedReader(new InputStreamReader(ins,"GBK"));
          StringBuffer sbf = new StringBuffer();
          String line = null;
          while ((line = br.readLine()) != null)
          {
          sbf.append(line);
          }

          br.close();
           
            
          String   result = sbf.toString();
          resultStr=result;
         System.out.println("getMethod.getResponseBodyAsString()返回的json原文:" +result+"json原文返回值"+"<br/>");
             
            JSONObject resjson = JSONObject.parseObject(result);
            String ret = resjson.getString("ret");
            if(ret.equals("0")){
            	   JSONObject data=resjson.getJSONObject("content");
                   String baifubaoSign = data.getString("sign");
                   String verifySign = new BfbSdkComm().verify_sign(resjson);
                 
              
           		
                   System.out.println("返回数据           :" + result + "<br/>  ");	
                   System.out.println("本地签名串            :" + verifySign + "本地签名串<br/>  ");
                   System.out.println("百付宝返回签名串:" + baifubaoSign + "百付宝返回签名串<br/> " );
                   System.out.println("本地签名串           : " + verifySign + "本地签名串  \n\r");
                   System.out.println("百付宝返回签名串: " + baifubaoSign + "百付宝返回签名串" );
       	    	   
        	    	   if(verifySign.equalsIgnoreCase(baifubaoSign))
       	    	   {
        	    		   System.out.println("验证签名通过 <br/>  ");
        	    		   System.out.println("验证签名通过\n\r  ");
       	    	   }else 
       	    	   {
       	    		 System.out.println("验证签名失败 <br/>  ");
       	    		 System.out.println("请求异常，请检查httpClient\n\r" );
       	    	   }
            	
            }else{
            	
            	 System.out.println("返回数据           :" + result + "<br/>  ");	
            }
         
	 
	      }catch (HttpException e) {    
	         // 发生致命的异常，可能是协议不对或者返回的内容有问题   
	    	  System.out.println("HttpException异常" );   
	    	  System.out.println("HttpException异常，请检查代码" );
	      } 
	      finally  
	      {    
	         /* 释放连接 */    
	    	  getMethod.releaseConnection();    
	      }    
	
		//在日志里面打印提交串
	     System.out.println("百度钱包扫码支付 getURL提交地址：："+getURL);
		//打印完成关闭日志
	     System.out.println(Level.OFF);
        return resultStr;


	}
    
	public String getServletInfo() {
		return "O2o_CodeCreateServlet";
	}
	public void init(ServletConfig config) throws ServletException {
		scon = config;
	}

}
